import re

from django.views import View
# 导入返回响应
from SaaSDevelTool.data_return_response import create_response
# 导入错误信息装饰器
from SaaSDevelTool.data_return_response import error_message_detection
# 获取数据库连接
from SaaSDevelTool.data_mysql_data import db
# 获取当前时间
from SaaSDevelTool.data_datetime_func import get_datatime
# 获取加密
from SaaSDevelTool.data_encode import aes_encrypt2

"""企业看板添加"""


def copy_databases_stored_procedure_rds2(databases_name, target_databases_name):
    """
    存储过程迁移，阿里云专用
    """
    # 定义存储过程名称
    conn = db.get_connection()
    cursor = conn.cursor()
    # 查询存储过程的定义
    cursor.execute(f"SHOW PROCEDURE STATUS WHERE Db = '{databases_name}';")
    # 获取查询的值
    procedure_definitions = cursor.fetchall()
    for procedure in procedure_definitions:
        procedure_name = procedure['Name']
        cursor.execute(f"USE {databases_name};")
        cursor.execute("SHOW CREATE PROCEDURE {}".format(procedure_name))
        procedure_definition = cursor.fetchone()
        if procedure_definition is not None:
            # 获取存储过程代码
            procedure_data = procedure_definition['Create Procedure']
            # 切换数据库
            cursor.execute(f"USE {target_databases_name};")
            # 检查存储过程是否已经存在于目标数据库中
            cursor.execute(f"SHOW PROCEDURE STATUS WHERE Db = '{target_databases_name}' AND Name = '{procedure_name}';")
            existing_procedure = cursor.fetchone()
            if existing_procedure:
                print(f"存储过程 {procedure_name} 在目标数据库 {target_databases_name} 中已存在。跳过...")
            else:
                # 创建存储过程
                cursor.execute(procedure_data)
    conn.commit()


class SaaSDataTenementCreate(View):
    @error_message_detection
    def post(self, request):
        # 获取企业名称
        tenement_name = request.POST.get("tenement_name")
        # 获取企业白色logo
        tenement_white_image = request.POST.get("tenement_white_image")
        # 获取企业彩色logo
        tenement_color_images = request.POST.get("tenement_color_images")
        # 获取企业注释
        tenement_remark = request.POST.get("tenement_remark")
        # 判断参数是否完整
        if not all([tenement_name, tenement_white_image, tenement_color_images]):
            return create_response(code=400, msg="添加失败，企业名称，企业白色logo,企业彩色logo为必选项。")

        # 判断企业名称
        if len(tenement_name) > 50:
            return create_response(code=400, msg="添加失败，企业名称最大字符位50个字符。")

        # 判断企业信息是否重复
        query_sum_up_tenement_table_sql = """
            SELECT
                tenement_name 
            FROM
                db_saas_center.sum_up_tenement_table 
            WHERE 
                tenement_name = '{}'
            ;""".format(tenement_name)

        # 进行查询操作
        query_sum_up_tenement_table_data = db.findOne(query_sum_up_tenement_table_sql)

        # 判断对应的参数
        if query_sum_up_tenement_table_data:
            return create_response(
                code=400,
                msg="添加失败，租户企业名称【{}】已存在，请更换名称再试。"
                .format(tenement_name))

        # 拼接插入语句
        create_sum_up_tenement_table_sql = """
            INSERT INTO 
                db_saas_center.sum_up_tenement_table(
                    tenement_name,
                    tenement_update_time,
                    tenement_white_image,
                    tenement_color_images,
                    tenement_remark)
                VALUES
                    ('{}','{}','{}','{}','{}')
                ;""".format(tenement_name, get_datatime(), tenement_white_image, tenement_color_images, tenement_remark)

        # 执行数据库插入语句
        enterprise_id = db.update(create_sum_up_tenement_table_sql)

        # 拼接创建数据库语句
        create_db_tenement_databases_sql = """ CREATE DATABASE db_tenement_{}""".format(enterprise_id)
        # 创建新库
        db.update(create_db_tenement_databases_sql)

        # 创建库所需表
        conn = db.get_connection()
        create_database_sql = """CALL db_tenement_0.create_database(%(gs_id)s, %(tabname_list)s)"""
        # 创建游标对象
        cursor = conn.cursor()
        # 执行存储过程
        cursor.execute(create_database_sql, {
            'gs_id': enterprise_id,
            'tabname_list': "base_info_contact_resource_all,base_info_contact_resource_all_home_page,base_info_contact_role,base_info_contact_settings,base_info_contact_user,map_contact_role_resource_all,map_contact_role_resource_all_home_page,base_info_role_resource_right"
        })

        # 迁移存储过程
        copy_databases_stored_procedure_rds2("db_tenement_0", "db_tenement_{}".format(enterprise_id))

        # 创建初始化用户组
        create_base_info_contact_role_sql = """
            INSERT INTO 
                db_tenement_{}.base_info_contact_role(
                    role_name,
                    role_create_user_id,
                    role_create_time 
            )
            VALUES 
                ('默认用户组',0,'{}')
            ;""".format(enterprise_id, get_datatime())
        # 执行语句
        db.update(create_base_info_contact_role_sql)

        # 创建初始用户名称
        user_name = "SaaS系统账户@{}".format(enterprise_id)

        # 创建初始用户手机号
        mobile = "13999999999"
        len_gs_id = len(str(enterprise_id))
        user_mobile = mobile[0:-len_gs_id] + str(enterprise_id)

        # 创建初始密码
        user_password_text = """saas_system_account_password_{}""".format(enterprise_id)
        encode_user_password_text = aes_encrypt2(user_password_text)

        # 创建用户的sql语句
        create_base_info_contact_user_sql = """
            INSERT INTO db_tenement_{}.base_info_contact_user(
                user_name, 
                user_password, 
                role_id, 
                is_del_type, 
                create_time, 
                create_user, 
                exploit_status, 
                manage_status,
                login_type
                )
            VALUES
                ('{}', '{}',1,0,'{}',1,0,0,'[]')
            ;""".format(enterprise_id, user_name, encode_user_password_text, get_datatime())
        # 执行语句
        user_id = db.update(create_base_info_contact_user_sql)

        # 拼接sql语句进行插入操作
        create_sum_saas_user_message_table_sql = """
            INSERT INTO 
                db_saas_center.sum_saas_user_message_table(
                    user_mobile,
                    user_tenement_id,
                    user_id,
                    user_code
                )
                VALUES 
                    ('{}',{},{},'')
            ;""".format(user_mobile, enterprise_id, user_id)

        db.update(create_sum_saas_user_message_table_sql)

        # 返回响应语句
        return create_response(code=200, msg="企业租户创建成功。")
